package com.jungle.framework.utils;

import com.jungle.common.core.domain.OptionVo;
import com.jungle.common.core.domain.PageQuery;
import com.jungle.common.utils.StringUtils;
import com.jungle.common.utils.spring.SpringUtils;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class AutoComputeUtils {
    @NotNull
    public static List<OptionVo> autoCompute(Class cls, String queryStr, String field, PageQuery pageQuery) {
        EntityManager entityManager = SpringUtils.getBean(EntityManager.class);
        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery cq = cb.createQuery(cls);
        Root root = cq.from(cls);
        List<Predicate> predicates = new ArrayList<>();
        if (StringUtils.isNotBlank(queryStr)) {
            predicates.add(cb.like(root.get(field), "%" + queryStr + "%"));
        }
        List<String> result = entityManager.createQuery(cq
                .distinct(true)
                .select(root.get(field))
                .where(predicates.toArray(Predicate[]::new))
            )
            .setFirstResult(0)
            .setMaxResults(pageQuery.getPageSize())
            .getResultList();
        return result.stream().map(v -> new OptionVo(null, v)).collect(Collectors.toList());
    }
}
